<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\admin;

use App\Controller\admin\common\Util;
use App\Model\Admin\Option;
use App\Model\Admin\User;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\View\RenderInterface;
use Psr\Http\Message\ResponseInterface;

#[AutoController]
class IndexController extends Crud
{
    /**
     * 无需登录的方法.
     * @var string[]
     */
    protected array $noNeedLogin = ['index'];

    /**
     * 不需要鉴权的方法.
     * @var string[]
     */
    protected array $noNeedAuth = ['dashboard'];

    /**
     * 后台主页.
     */
    public function index(RenderInterface $render): ResponseInterface
    {
        clearstatcache();
        $admin = admin();
        if (!$admin) {
            $name = 'system_config';
            $config = Option::where('name', $name)->value('value');
            $config = json_decode($config, true);
            $title = $config['logo']['title'] ?? 'hyperf管理系统';
            $logo = $config['logo']['image'] ?? '/admin/images/logo.png';
            return $render->render('account/login', ['logo' => $logo, 'title' => $title]);
        }
        return $render->render('index/index');
    }

    /**
     * 仪表板
     */
    public function dashboard(RenderInterface $render): ResponseInterface
    {
        // 今日新增用户数
        $today_user_count = User::where('created_at', '>', date('Y-m-d') . ' 00:00:00')->count();
        // 7天内新增用户数
        $day7_user_count = User::where('created_at', '>', date('Y-m-d H:i:s', time() - 7 * 24 * 60 * 60))->count();
        // 30天内新增用户数
        $day30_user_count = User::where('created_at', '>', date('Y-m-d H:i:s', time() - 30 * 24 * 60 * 60))->count();
        // 总用户数
        $user_count = User::count();
        // mysql版本
        $version = Db::select('select VERSION() as version');
        $mysql_version = $version[0]['version'] ?? 'unknown';

        $day7_detail = [];
        $now = time();
        for ($i = 0; $i < 7; ++$i) {
            $date = date('Y-m-d', $now - 24 * 60 * 60 * $i);
            $day7_detail[substr($date, 5)] = User::where('created_at', '>', "{$date} 00:00:00")
                ->where('created_at', '<', "{$date} 23:59:59")->count();
        }

        return $render->render('index/dashboard', [
            'today_user_count' => $today_user_count,
            'day7_user_count' => $day7_user_count,
            'day30_user_count' => $day30_user_count,
            'user_count' => $user_count,
            'php_version' => PHP_VERSION,
            'workerman_version' => '5.0',
            'webman_version' => '3.0',
            'admin_version' => '0.1',
            'mysql_version' => $mysql_version,
            'os' => PHP_OS,
            'day7_detail' => array_reverse($day7_detail),
        ]);
    }
}
